﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>07_DrawTriangleFan</title>
    <link href="css/common.css" rel="stylesheet" />
</head>
<body>
    <canvas id="mycanvas"></canvas>
    <script id="shader-vs" type="x-shader/x-vertex">
        attribute vec4 aPosition;

        void main() {
        gl_Position = aPosition;
        }
    </script>
    <script id="shader-fs" type="x-shader/x-fragment">
        void main() {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
        }
    </script>
    <script>
        var canvas = document.getElementById('mycanvas');
        canvas.width = canvas.clientWidth;
        canvas.height = canvas.clientHeight;

        var gl = canvas.getContext('webgl');

        var vertexShader = gl.createShader(gl.VERTEX_SHADER);
        gl.shaderSource(vertexShader, document.getElementById('shader-vs').innerHTML);
        gl.compileShader(vertexShader);

        var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
        gl.shaderSource(fragmentShader, document.getElementById('shader-fs').innerHTML);
        gl.compileShader(fragmentShader);

        var shaderProgram = gl.createProgram();
        gl.attachShader(shaderProgram, vertexShader);
        gl.attachShader(shaderProgram, fragmentShader);
        gl.linkProgram(shaderProgram);
        gl.useProgram(shaderProgram);

        var aPosition = gl.getAttribLocation(shaderProgram, 'aPosition');

        gl.clearColor(0.0, 0.0, 0.0, 1.0);
        gl.clear(gl.COLOR_BUFFER_BIT);

        var vertexBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
            -0.7, 0.4,
            -0.7, -0.5,
            -0.3, -0.5,

            0.0, 0.0,

            -0.3, 0.6
        ]), gl.STATIC_DRAW);

        gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0); // 2是2个元素为一个点
        gl.enableVertexAttribArray(aPosition);

        gl.drawArrays(gl.TRIANGLE_FAN, 0, 5); // 5是顶点数量

        // gl.TRIANGLE_FAN
        // gl.TRIANGLE_FAN与gl.TRIANGLE_STRIP类似，它前三个顶点组成一个三角形。
        // 以后每多一个点，都与它前面一个点和第一个点组成一个三角形，形成一个类似扇形的形状。
    </script>
</body>
</html>
